package com.cuit.riskassessment.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.BeforeClass;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;
import org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping;

/**
 * 用于单元测试Action
 * @author Yang_Zhiqin
 *
 */
@SuppressWarnings({  "deprecation" })
public class JunitActionBase {
	private static HandlerMapping handlerMapping;
	private static HandlerAdapter handleraDapter;
	protected static XmlWebApplicationContext context;
	 @BeforeClass  
	public static void setUp()
	{
		try{
		if(handlerMapping == null)
		{ 
			context = new XmlWebApplicationContext();
			context.setConfigLocation("classpath:com/conf/application.xml");
			MockServletContext msc = new MockServletContext();
			context.setServletContext(msc);
			context.refresh();
			msc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,   
			handlerMapping = (HandlerMapping) context  
                    .getBean(DefaultAnnotationHandlerMapping.class));  
            handleraDapter = (HandlerAdapter) context.getBean(context.getBeanNamesForType(AnnotationMethodHandlerAdapter.class)[0]);     
		}
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	 /** 
     * 执行request对象请求的action 
     *  
     * @param request 
     * @param response 
     * @return 
     * @throws Exception 
     */  
    public ModelAndView excuteAction(HttpServletRequest request, HttpServletResponse response)  
    		throws Exception {  
        HandlerExecutionChain chain = handlerMapping.getHandler(request);  
        final ModelAndView model = handleraDapter.handle(request, response,  
                chain.getHandler());  
        return model;  
    }  
    
    
}
